<?php
namespace app\api\controller\kuyou\applet;
use think\Db;
class GoodsStock extends Common
{
    protected $noNeedRight = ['goodsStockInfo'];

    public function index()
    {
        if ($this->request->isPost()) {
            $where = [];
            $createtime = $this->request->post('createtime');
            if(!empty($createtime)){
                $str = explode('~',$createtime);
                if(isset($str[0]) && isset($str[1])){
                    $where['gs.createtime'] = ["BETWEEN", [strtotime($str[0]),strtotime($str[1])]];
                }
            }
            $goods_id = $this->request->post('goods_id');
            if(!empty($goods_id)){
                $where['gs.goods_id'] = ["in", $goods_id];
            }
            $stores_id = $this->request->post('stores_id');
            if(!empty($stores_id)){
                $where['gs.stores_id'] = ["in", $stores_id];
            }

            $list = Db::name('kuyou_goods_stock')->alias('gs')
                ->join('kuyou_goods g','g.goods_code=gs.goods_code')
                ->where($where)
                ->group('g.goods_code,gs.attribute_id')
                ->field('gs.id,gs.goods_code,sum(gs.stock) as stock,sum(gs.cost_money) as cost_money,gs.attribute_id,
                g.goods_type_id,g.goods_code,g.goods_name,g.goods_image,g.goods_specification_id,g.note,g.unit_id,g.more_unit,g.goods_barcode')
                ->select();
            foreach ($list as $list_k=>$list_v) {
                $list[$list_k]['goods'] = Db::name('kuyou_goods')->where(['goods_code'=>$list_v['goods_code']])
                    ->field('goods_type_id,goods_code,goods_name,goods_specification_id,note,unit_id,more_unit,goods_barcode')
                    ->find();
            }

            $number_decimal = Db::name('kuyou_sets')->where(['name'=>'number_decimal'])->value('value');
            $price_decimal = Db::name('kuyou_sets')->where(['name'=>'price_decimal'])->value('value');
            $checkdate = Db::name('kuyou_checkout')->order(['checkdate'=>'DESC'])->value('checktime');
            $enable_time = Db::name('kuyou_sets')->where(['name'=>'enable_time'])->value('value');
            $valuation_set= Db::name('kuyou_sets')->where(['name'=>'valuation'])->value('value');//计算方法
            $stores_set= Db::name('kuyou_sets')->where(['name'=>'stores'])->value('is_checked');//是否分仓
            if($valuation_set!=2){
                $valuation_set = 1;
            }
            if($stores_set!=1){
                $stores_set = 0;
            }

            $price_taxes= Db::name('kuyou_sets')->where(['name'=>'price_taxes'])->value('is_checked');
            $taxes_set= Db::name('kuyou_sets')->where(['name'=>'taxes'])->field('value,is_checked')->find();
            $stores_ids = Db::name('kuyou_stores')->where(['status'=>'1'])->column('id');

            foreach ($list as $list_k=>$list_v){
                $purchase_money = Db::name('kuyou_goods_purchase_info')->where(['pi.goods_code'=>$list_v['goods_code'],'p.examine_status'=>'1'])->alias('pi')
                    ->join('kuyou_goods_purchase p','p.purchase_code=pi.purchase_code')
                    ->field('sum(pi.all_money) as all_money,sum(pi.basic_nmber) as basic_nmber')->find();
                $result = (new Commons())->getGoodsCostPrice(
                    $list_v['goods_code'],
                    $number_decimal,
                    $price_decimal,
                    $checkdate,
                    $enable_time,
                    $valuation_set,
                    $stores_set,
                    $price_taxes,
                    $taxes_set,
                    $stores_ids
                );
                if(isset($result[0]['cost_all']) && isset($result[0]['basic_nmber'])){
                    $cost_money = $purchase_money['all_money']-$result[0]['cost_all'];
                    $cost_number = $purchase_money['basic_nmber']-$result[0]['basic_nmber'];
                }else{
                    $cost_money = $purchase_money['all_money'];
                    $cost_number = $purchase_money['basic_nmber'];
                }
                if($cost_number!=0){
                    $unit_price = round($cost_money/$cost_number,$price_decimal);
                }else{
                    $unit_price = 0;
                }
                $list[$list_k]['unit_price'] = $unit_price;
                $list[$list_k]['cost_money'] = $cost_money;

                $list[$list_k]['type_name'] = Db::name('kuyou_goods_type')->where(['id'=>$list_v['goods_type_id']])->value('supplier_type_name');
                //单位信息
                $unit = Db::name('kuyou_unit')->where(['id'=>$list_v['unit_id']])->field('id,name')->find();
                $list[$list_k]['unit_name'] = $unit['name'];
                $max_unit = 1;
                $unit_arr = [];
                $more_unit_num = '';
                if($unit){
                    $unit_arr[] = ['name'=>$unit['name'],'advance_rate'=>1];
                    if($list_v['more_unit']==1){
                        $more_unit = Db::name('kuyou_unit_conversion')->alias('uc')
                            ->join('kuyou_unit u','u.id=uc.vice_unit')
                            ->where(['uc.main_unit'=>$unit['id']])
                            ->order('uc.advance_rate','ASC')
                            ->field('uc.vice_unit,u.name,u.id,uc.advance_rate')
                            ->select();
                        foreach ($more_unit as $unit_k=>$unit_v){
                            $unit_arr[] = ['name'=>$unit_v['name'],'advance_rate'=>$unit_v['advance_rate']];
                            if($unit_v['advance_rate']>$max_unit){
                                $max_unit = $unit_v['advance_rate'];
                            }
                        }
                        $unitconversion = '';
                        $unit_arr = (new Commons())->arraySequence($unit_arr,'advance_rate','SORT_DESC');
                        foreach ($unit_arr as $unit_arr_k=>$unit_arr_v){
                            if(!empty($unitconversion)){
                                $unitconversion .= '=';
                            }else{
                                $more_unit_num .= round(($list_v['stock']/$unit_arr_v['advance_rate']),$number_decimal).$unit_arr_v['name'];
                            }
                            $unitconversion .= round(($max_unit/$unit_arr_v['advance_rate']),$number_decimal).$unit_arr_v['name'];
                        }
                        $list[$list_k]['unitconversion'] = $unitconversion;
                        $list[$list_k]['more_unit_num'] = $more_unit_num;
                    }
                }
            }
            $storesList = Db::name('kuyou_stores')->where(['status'=>'1'])->field('id,name')->select();
            $countArr = [];
            foreach ($list as $list_k=>$list_v){
                if(isset($countArr['stock'])){
                    $countArr['stock'] += $list_v['stock'];
                }else{
                    $countArr['stock'] = $list_v['stock'];
                }
                if(isset($countArr['cost_money'])){
                    $countArr['cost_money'] += $list_v['cost_money'];
                }else{
                    $countArr['cost_money'] = $list_v['cost_money'];
                }
                $list[$list_k]['goods_code'] = $list_v['goods_code'];
                $list[$list_k]['goods_name'] = $list_v['goods_name'];
                $list[$list_k]['goods_specification_id'] = $list_v['goods_specification_id'];
                $list[$list_k]['note'] = $list_v['note'];
                $list[$list_k]['goods_barcode'] = $list_v['goods_barcode'];
                $list[$list_k]['goods_image'] = $list_v['goods_image'];
                //按属性分组显示
                $attribute_ids = Db::name('kuyou_aux_combination')->where(['id'=>$list_v['attribute_id']])->value('attr_ids');
                if($attribute_ids){
                    $attribute_ids = explode('&',$attribute_ids);
                    $attribute = Db::name('kuyou_auxiliary')->where(['id'=>['in',$attribute_ids]])->column('name');
                    $attribute_name = implode('/',$attribute);
                    $list[$list_k]['goods_name'] = $list_v['goods_name'].'_'.$attribute_name;
                }

                foreach ($storesList as $storesList_k=>$storesList_v){
                    $list2 = Db::name('kuyou_goods_stock')->alias('gs')
                        ->join('kuyou_goods g','g.goods_code=gs.goods_code')
                        ->where($where)
                        ->where(['gs.stores_id'=>$storesList_v['id'],'gs.goods_code'=>$list_v['goods_code']])
                        ->where(['gs.attribute_id'=>$list_v['attribute_id']])
                        ->group('gs.goods_code')
                        ->field('sum(gs.stock) as stock,sum(gs.cost_money) as cost_money')
                        ->find();
                    if($list2){
                        $list2['unit_price'] = $list_v['unit_price'];
                        $list2['cost_money'] = round( ($list_v['unit_price']*$list2['stock']), $price_decimal);

                        $unit = Db::name('kuyou_unit')->where(['id'=>$list_v['unit_id']])->field('id,name')->find();
                        if($unit){
                            if($list_v['more_unit']==1){
                                $more_unit = Db::name('kuyou_unit_conversion')->alias('uc')
                                    ->join('kuyou_unit u','u.id=uc.vice_unit')
                                    ->where(['uc.main_unit'=>$unit['id']])
                                    ->order('uc.advance_rate','DESC')
                                    ->field('uc.vice_unit,u.name,u.id,uc.advance_rate')
                                    ->find();
                                $more_unit_num = '';
                                if($more_unit){
                                    $more_unit_num .= round(($list2['stock']/$more_unit['advance_rate']),$number_decimal).$more_unit['name'];
                                }
                                $list2['more_unit_num'] = $more_unit_num;
                            }
                        }
                        if(!isset($list2['more_unit_num'])){
                            $list2['more_unit_num'] = '';
                        }
                        $list[$list_k]['stock'.$storesList_v['id']] = $list2['stock'];
                        $list[$list_k]['cost_money'.$storesList_v['id']] = $list2['cost_money'];
                        $list[$list_k]['unit_price'.$storesList_v['id']] = $list2['unit_price'];
                        $list[$list_k]['more_unit_num'.$storesList_v['id']] = $list2['more_unit_num'];

                        if(isset($countArr['stock'.$storesList_v['id']])){
                            $countArr['stock'.$storesList_v['id']] += $list2['stock'];
                        }else{
                            $countArr['stock'.$storesList_v['id']] = $list2['stock'];
                        }
                        if(isset($countArr['cost_money'.$storesList_v['id']])){
                            $countArr['cost_money'.$storesList_v['id']] += $list2['cost_money'];
                        }else{
                            $countArr['cost_money'.$storesList_v['id']] = $list2['cost_money'];
                        }
                    }
                }
            }


            $sumArr = [];
            if(isset($countArr['stock']) && $countArr['stock']>0){
                $sumArr[] = ['unit_price_count'=>round(($countArr['cost_money']/$countArr['stock']),$price_decimal),'id'=>''];
            }else{
                $sumArr[] = ['unit_price_count'=>0,'id'=>''];
            }
            foreach ($storesList as $storesList_k=>$storesList_v){
                if(isset($countArr['stock'.$storesList_v['id']]) && $countArr['stock'.$storesList_v['id']]>0){
                    $sumArr[] = ['unit_price_count'=>round(($countArr['cost_money'.$storesList_v['id']]/$countArr['stock'.$storesList_v['id']]),$price_decimal),'id'=>$storesList_v['id']];
                }else{
                    $sumArr[] = ['unit_price_count'=>0,'id'=>$storesList_v['id']];
                }
            }
            foreach ($sumArr as $sumArr_k=>$sumArr_v){
                foreach ($list as $list_k=>$list_v){
                    if($sumArr_v['id']>0){
                        if(isset($sumArr[$sumArr_k]['stock'])){
                            $sumArr[$sumArr_k]['stock'] += (isset($list_v['stock'.$sumArr_v['id']])?$list_v['stock'.$sumArr_v['id']]:0);
                            $sumArr[$sumArr_k]['cost_money'] += (isset($list_v['cost_money'.$sumArr_v['id']])?$list_v['cost_money'.$sumArr_v['id']]:0);
                        }else{
                            $sumArr[$sumArr_k]['stock'] = (isset($list_v['stock'.$sumArr_v['id']])?$list_v['stock'.$sumArr_v['id']]:0);
                            $sumArr[$sumArr_k]['cost_money'] = (isset($list_v['cost_money'.$sumArr_v['id']])?$list_v['cost_money'.$sumArr_v['id']]:0);
                        }
                    }else{
                        if(isset($sumArr[$sumArr_k]['stock'])){
                            $sumArr[$sumArr_k]['stock'] += $list_v['stock'];
                            $sumArr[$sumArr_k]['cost_money'] += $list_v['cost_money'];
                        }else{
                            $sumArr[$sumArr_k]['stock'] = $list_v['stock'];
                            $sumArr[$sumArr_k]['cost_money'] = $list_v['cost_money'];
                        }
                    }
                }
            }
            foreach ($sumArr as $sumArr_k=>$sumArr_v){
                $sumArr[$sumArr_k]['stock'] = isset($sumArr_v['stock'])?round($sumArr_v['stock'],$number_decimal):0;
                $sumArr[$sumArr_k]['cost_money'] = isset($sumArr_v['cost_money'])?round($sumArr_v['cost_money'],$number_decimal):0;
            }
            $result = array("count" => sizeof($list), "list" => $list, "countArr" => $sumArr,'storesList'=>$storesList);

            if(isset($result['list']) && isset($result['count'])){
                $this->success('查询成功',$result,200);
            }else{
                $this->error('查询失败','',406);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }
    /**
     * 商品库存余额详情
     * @ApiMethod (POST)
     */
    public function goodsStockInfo()
    {
        if ($this->request->isPost()) {
            $where = [];
            $goods_id = $this->request->post('goods_id');
            if(!empty($goods_id)){
                $where['gs.goods_id'] = ["in", $goods_id];
            }
            $goods_code = $this->request->post('goods_code');
            if(!empty($goods_code)){
                $where['gs.goods_code'] = ["in", $goods_code];
            }
            $attribute_id = $this->request->post('attribute_id');
            if(!empty($attribute_id)){
                $where['gs.attribute_id'] = ["in", $attribute_id];
            }

            $list = Db::name('kuyou_goods_stock')->alias('gs')
                ->join('kuyou_goods g','g.goods_code=gs.goods_code')
                ->where($where)
                ->group('g.goods_code,gs.attribute_id')
                ->field('gs.id,gs.goods_code,sum(gs.stock) as stock,sum(gs.cost_money) as cost_money,gs.attribute_id,
                g.goods_type_id,g.goods_code,g.goods_name,g.goods_image,g.goods_specification_id,g.note,g.unit_id,g.more_unit,g.goods_barcode')
                ->select();

            $number_decimal = Db::name('kuyou_sets')->where(['name'=>'number_decimal'])->value('value');
            $price_decimal = Db::name('kuyou_sets')->where(['name'=>'price_decimal'])->value('value');
            $checkdate = Db::name('kuyou_checkout')->order(['checkdate'=>'DESC'])->value('checktime');
            $enable_time = Db::name('kuyou_sets')->where(['name'=>'enable_time'])->value('value');
            $valuation_set= Db::name('kuyou_sets')->where(['name'=>'valuation'])->value('value');//计算方法
            $stores_set= Db::name('kuyou_sets')->where(['name'=>'stores'])->value('is_checked');//是否分仓
            if($valuation_set!=2){
                $valuation_set = 1;
            }
            if($stores_set!=1){
                $stores_set = 0;
            }

            $price_taxes= Db::name('kuyou_sets')->where(['name'=>'price_taxes'])->value('is_checked');
            $taxes_set= Db::name('kuyou_sets')->where(['name'=>'taxes'])->field('value,is_checked')->find();
            $stores_ids = Db::name('kuyou_stores')->where(['status'=>'1'])->column('id');

            foreach ($list as $list_k=>$list_v){
                $purchase_money = Db::name('kuyou_goods_purchase_info')->where(['pi.goods_code'=>$list_v['goods_code'],'p.examine_status'=>'1'])->alias('pi')
                    ->join('kuyou_goods_purchase p','p.purchase_code=pi.purchase_code')
                    ->field('sum(pi.all_money) as all_money,sum(pi.basic_nmber) as basic_nmber')->find();
                $result = (new Commons())->getGoodsCostPrice(
                    $list_v['goods_code'],
                    $number_decimal,
                    $price_decimal,
                    $checkdate,
                    $enable_time,
                    $valuation_set,
                    $stores_set,
                    $price_taxes,
                    $taxes_set,
                    $stores_ids
                );
                if(isset($result[0]['cost_all']) && isset($result[0]['basic_nmber'])){
                    $cost_money = $purchase_money['all_money']-$result[0]['cost_all'];
                    $cost_number = $purchase_money['basic_nmber']-$result[0]['basic_nmber'];
                }else{
                    $cost_money = $purchase_money['all_money'];
                    $cost_number = $purchase_money['basic_nmber'];
                }
                if($cost_number!=0){
                    $unit_price = round($cost_money/$cost_number,$price_decimal);
                }else{
                    $unit_price = 0;
                }
                $list[$list_k]['unit_price'] = $unit_price;
                $list[$list_k]['cost_money'] = $cost_money;
                $list[$list_k]['type_name'] = Db::name('kuyou_goods_type')->where(['id'=>$list_v['goods_type_id']])->value('supplier_type_name');
                //单位信息
                $unit = Db::name('kuyou_unit')->where(['id'=>$list_v['unit_id']])->field('id,name')->find();
                $list[$list_k]['unit_name'] = $unit['name'];
                $max_unit = 1;
                $unit_arr = [];
                $more_unit_num = '';
                if($unit){
                    $unit_arr[] = ['name'=>$unit['name'],'advance_rate'=>1];
                    if($list_v['more_unit']==1){
                        $more_unit = Db::name('kuyou_unit_conversion')->alias('uc')
                            ->join('kuyou_unit u','u.id=uc.vice_unit')
                            ->where(['uc.main_unit'=>$unit['id']])
                            ->order('uc.advance_rate','ASC')
                            ->field('uc.vice_unit,u.name,u.id,uc.advance_rate')
                            ->select();
                        foreach ($more_unit as $unit_k=>$unit_v){
                            $unit_arr[] = ['name'=>$unit_v['name'],'advance_rate'=>$unit_v['advance_rate']];
                            if($unit_v['advance_rate']>$max_unit){
                                $max_unit = $unit_v['advance_rate'];
                            }
                        }
                        $unitconversion = '';
                        $unit_arr = (new Commons())->arraySequence($unit_arr,'advance_rate','SORT_DESC');
                        foreach ($unit_arr as $unit_arr_k=>$unit_arr_v){
                            if(!empty($unitconversion)){
                                $unitconversion .= '=';
                            }else{
                                $more_unit_num .= round(($list_v['stock']/$unit_arr_v['advance_rate']),$number_decimal).$unit_arr_v['name'];
                            }
                            $unitconversion .= round(($max_unit/$unit_arr_v['advance_rate']),$number_decimal).$unit_arr_v['name'];
                        }
                        $list[$list_k]['unitconversion'] = $unitconversion;
                        $list[$list_k]['more_unit_num'] = $more_unit_num;
                    }
                }
            }
            $storesList = Db::name('kuyou_stores')->where(['status'=>'1'])->field('id,name')->select();
            $countArr = [];
            foreach ($list as $list_k=>$list_v){
                if(isset($countArr['stock'])){
                    $countArr['stock'] += $list_v['stock'];
                }else{
                    $countArr['stock'] = $list_v['stock'];
                }
                if(isset($countArr['cost_money'])){
                    $countArr['cost_money'] += $list_v['cost_money'];
                }else{
                    $countArr['cost_money'] = $list_v['cost_money'];
                }
                $list[$list_k]['goods_code'] = $list_v['goods_code'];
                $list[$list_k]['goods_name'] = $list_v['goods_name'];
                $list[$list_k]['goods_specification_id'] = $list_v['goods_specification_id'];
                $list[$list_k]['note'] = $list_v['note'];
                $list[$list_k]['goods_barcode'] = $list_v['goods_barcode'];
                $list[$list_k]['goods_image'] = $list_v['goods_image'];
                //按属性分组显示
                $attribute_ids = Db::name('kuyou_aux_combination')->where(['id'=>$list_v['attribute_id']])->value('attr_ids');
                if($attribute_ids){
                    $attribute_ids = explode('&',$attribute_ids);
                    $attribute = Db::name('kuyou_auxiliary')->where(['id'=>['in',$attribute_ids]])->column('name');
                    $attribute_name = implode('/',$attribute);
                    $list[$list_k]['goods_name'] = $list_v['goods_name'].'_'.$attribute_name;
                }

                $storesInfo = [];
                foreach ($storesList as $storesList_k=>$storesList_v){
                    $list2 = Db::name('kuyou_goods_stock')->alias('gs')
                        ->join('kuyou_goods g','g.goods_code=gs.goods_code')
                        ->where($where)
                        ->where(['gs.stores_id'=>$storesList_v['id'],'gs.goods_code'=>$list_v['goods_code']])
                        ->where(['gs.attribute_id'=>$list_v['attribute_id']])
                        ->group('gs.goods_code')
                        ->field('sum(gs.stock) as stock,sum(gs.cost_money) as cost_money')
                        ->find();
                    if($list2){
                        $list2['unit_price'] = $list_v['unit_price'];
                        $list2['cost_money'] = round( ($list_v['unit_price']*$list2['stock']), $price_decimal);

                        $unit = Db::name('kuyou_unit')->where(['id'=>$list_v['unit_id']])->field('id,name')->find();
                        if($unit){
                            if($list_v['more_unit']==1){
                                $more_unit = Db::name('kuyou_unit_conversion')->alias('uc')
                                    ->join('kuyou_unit u','u.id=uc.vice_unit')
                                    ->where(['uc.main_unit'=>$unit['id']])
                                    ->order('uc.advance_rate','DESC')
                                    ->field('uc.vice_unit,u.name,u.id,uc.advance_rate')
                                    ->find();
                                $more_unit_num = '';
                                if($more_unit){
                                    $more_unit_num .= round(($list2['stock']/$more_unit['advance_rate']),$number_decimal).$more_unit['name'];
                                }
                                $list2['more_unit_num'] = $more_unit_num;
                            }
                        }
                        if(!isset($list2['more_unit_num'])){
                            $list2['more_unit_num'] = '';
                        }
                        $storesInfo[] = [
                            'stores_id' => $storesList_v['id'],
                            'stores_name' => $storesList_v['name'],
                            'stock' => $list2['stock'],
                            'cost_money' => $list2['cost_money'],
                            'unit_price' => $list2['unit_price'],
                            'more_unit_num' => $list2['more_unit_num'],
                        ];

                        if(isset($countArr['stock'.$storesList_v['id']])){
                            $countArr['stock'.$storesList_v['id']] += $list2['stock'];
                        }else{
                            $countArr['stock'.$storesList_v['id']] = $list2['stock'];
                        }
                        if(isset($countArr['cost_money'.$storesList_v['id']])){
                            $countArr['cost_money'.$storesList_v['id']] += $list2['cost_money'];
                        }else{
                            $countArr['cost_money'.$storesList_v['id']] = $list2['cost_money'];
                        }
                    }
                }
                $list[$list_k]['storesInfo'] = $storesInfo;
            }
            $sumArr = [];
            if(isset($countArr['stock']) && $countArr['stock']>0){
                $sumArr[] = ['unit_price_count'=>round(($countArr['cost_money']/$countArr['stock']),$price_decimal),'id'=>''];
            }else{
                $sumArr[] = ['unit_price_count'=>0,'id'=>''];
            }
            foreach ($storesList as $storesList_k=>$storesList_v){
                if(isset($countArr['stock'.$storesList_v['id']]) && $countArr['stock'.$storesList_v['id']]>0){
                    $sumArr[] = ['unit_price_count'=>round(($countArr['cost_money'.$storesList_v['id']]/$countArr['stock'.$storesList_v['id']]),$price_decimal),'id'=>$storesList_v['id']];
                }else{
                    $sumArr[] = ['unit_price_count'=>0,'id'=>$storesList_v['id']];
                }
            }
            $result = array("info" => isset($list[0])?$list[0]:[], "countArr" => $sumArr,'storesList'=>$storesList);

            if(isset($result['info'])){
                $this->success('查询成功',$result,200);
            }else{
                $this->error('查询失败','',406);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }
}
